%%% -------------------------------------------------------------------
%%% Author  : tangj
%%% Description :
%%%
%%% Created : 2012-9-22
%%% -------------------------------------------------------------------
-module(gateway_server).

-behaviour(gen_server).

-export([start_link/2]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
		 terminate/2, code_change/3]).

-define(TCP_OPTIONS, [binary, 
					  {packet, 0}, 
					  {active, false}, 
					  {reuseaddr, true}, 
					  {nodelay, false}, 
					  {delay_send, true}, 
					  {send_timeout, 5000}, 
					  {keepalive, true}, 
					  {exit_on_close, true}]).

%% --------------------------------------------------------------------
start_link(AcceptorCount, Port) ->
	{ok, Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, {AcceptorCount, Port}, []),
	io:format("gateway_server start_link~p~n", [Pid]),
	{ok, Pid}.

%% --------------------------------------------------------------------

init({AcceptorCount, Port}) ->
	process_flag(trap_exit, true),
	gen_server:cast(self(), {listen, AcceptorCount, Port}),
	{ok, state}.


handle_call(_Rec, _From, Status) ->
	{reply, ok, Status}.

handle_cast({listen, AcceptorCount, Port}, Status) ->
	case gen_tcp:listen(Port, ?TCP_OPTIONS) of
		{ok, LSock} ->
			tool:for(1, AcceptorCount, 
					 fun(X) ->
							 supervisor:start_child(
							   gateway_sup, 
							   {lists:concat([gateway_acceptor_, X]), 
								{gateway_acceptor, start_link, [LSock]},
								temporary, 
								10000, 
								worker, 
								[gateway_acceptor]})
					 end),
			{noreply, LSock};
		{error, Reason} ->
			{stop, {cannot_listen, Reason}, Status}
	end;

handle_cast(_Rec, Status) ->
	{noreply, Status}.

handle_info(_Info, Status) ->
	{noreply, Status}.

terminate(_Reason, Status) ->
	gen_tcp:close(Status),
	ok.

code_change(_OldVsn, Status, _Extra)->
	{ok, Status}.
